package com.tich.program.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.tich.constant.ExceptionConstant;
import com.tich.constant.RabbitMqConstant;
import com.tich.exception.ProgramCategoryNotFoundException;
import com.tich.exception.SaveException;
import com.tich.program.domain.dto.CategoryDeleteDTO;
import com.tich.program.domain.dto.CategorySaveDTO;
import com.tich.program.domain.entity.ProgramCategory;
import com.tich.program.domain.vo.ProgramCategoryVO;
import com.tich.program.mapper.ProgramCategoryMapper;
import com.tich.program.service.IProgramCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class ProgramCategoryServiceImpl extends ServiceImpl<ProgramCategoryMapper, ProgramCategory> implements IProgramCategoryService {

    @Autowired
    private ProgramCategoryMapper programCategoryMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 批量新增节目种类
     * @param categorySaveDTO
     * @return
     * */
    @Transactional
    public void addBatch(CategorySaveDTO categorySaveDTO) {
        List<ProgramCategory> programCategories = categorySaveDTO.getCategoryNames().stream().map(name -> new ProgramCategory().setCategory(name)).toList();
        saveBatch(programCategories);
    }

    /**
     * 查询所有节目种类
     * @return
     * */
    public List<ProgramCategoryVO> queryProgramCategory() {
        List<ProgramCategory> programCategories = lambdaQuery()
                .select(ProgramCategory::getId, ProgramCategory::getCategory)
                .orderByAsc(ProgramCategory::getId)
                .list();
        return programCategories.stream()
                .map(programCategory -> new ProgramCategoryVO()
                        .setId(programCategory.getId())
                        .setCategory(programCategory.getCategory()))
                .toList();
    }

    /**
     * 批量删除节目种类
     * @param categoryDeleteDTO
     * @return
     * */
    public void deleteProgramCategorys(CategoryDeleteDTO categoryDeleteDTO) {
        //1.根据ids查询
        List<ProgramCategory> programCategories = programCategoryMapper.selectByIds(categoryDeleteDTO.getIds());
        if(programCategories.isEmpty()){
            throw new ProgramCategoryNotFoundException(ExceptionConstant.PROGRAM_CATEGORY_NOT_FOUND);
        }
        //2.删除节目种类
        removeBatchByIds(categoryDeleteDTO.getIds());
        //3.将消息发送至交换机
        rabbitTemplate.convertAndSend(RabbitMqConstant.PROGRAM_DIRECT,
                RabbitMqConstant.PROGRAM_CATEGORY_DELETE_KEY,
                programCategories);
    }
}
